import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Solution1537 {
    public int maxSum(int[] nums1, int[] nums2) {
        Map<Integer,Integer> m1=new HashMap<>();
        Map<Integer,Integer> m2=new HashMap<>();
        for (int i=0;i<nums1.length;i++){
            m1.put(nums1[i],i);
        }
        for (int i=0;i<nums2.length;i++){
            m2.put(nums2[i],i);
        }
        long[] f1=new long[nums1.length+1];
        long[] f2=new long[nums2.length+1];
        Arrays.fill(f1,-1);
        Arrays.fill(f2,-1);
        f1[0]=0;
        f2[0]=0;
        dfs(f1,f2,nums1,nums2,m1,m2,1,nums1.length);
        dfs(f1,f2,nums1,nums2,m1,m2,2,nums2.length);
        return (int)(Math.max(f1[nums1.length],f2[nums2.length])%1000000007);
    }

    private void dfs(long[] f1, long[] f2, int[] nums1, int[] nums2, Map<Integer, Integer> m1, Map<Integer, Integer> m2, int state, int k) {
        if (state==1){
            if (f1[k]!=-1){
                return;
            }
            dfs(f1,f2,nums1,nums2,m1,m2,1,k-1);
            f1[k]=f1[k-1]+nums1[k-1];
            if (m2.containsKey(nums1[k-1])){
                int t=m2.get(nums1[k-1]);
                dfs(f1,f2,nums1,nums2,m1,m2,2,t);
                f1[k]=Math.max(f1[k],f2[t]+nums1[k-1]);
            }
        }else {
            if (f2[k]!=-1){
                return;
            }
            dfs(f1,f2,nums1,nums2,m1,m2,2,k-1);
            f2[k]=f2[k-1]+nums2[k-1];
            if (m1.containsKey(nums2[k-1])){
                int t=m1.get(nums2[k-1]);
                dfs(f1,f2,nums1,nums2,m1,m2,1,t);
                f2[k]=Math.max(f2[k],f1[t]+nums2[k-1]);
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(new Solution1537().maxSum(new int[]{2,4,5,8,10},new int[]{4,6,8,9}));
    }
}
